package com.example.controller;

import com.example.controller.request.SendCodeRequest;
import com.example.enums.BizCodeEnum;
import com.example.enums.SendCodeEnum;
import com.example.service.NotifyService;
import com.example.utils.CommonUtil;
import com.example.utils.JsonData;
import com.google.code.kaptcha.Producer;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.imageio.ImageIO;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.util.concurrent.TimeUnit;

/**
 * @author yinxin
 * @version 1.0
 * @Description: 登录模块代码
 * @date 2022/6/416:23
 */
@RestController
@RequestMapping("/api/notify/v1")
@Slf4j
public class NotifyController {


    @Autowired
    NotifyService notifyService;

    @Autowired
    StringRedisTemplate redisTemplate;

    @Autowired
    private Producer captchaProducer;

    /**
     * 验证码过期时间
     */
    private static final long CAPTCHA_CODE_EXPIRED = 1000 * 10 * 60;

    /**
     * 图形验证码
     *
     * @param request
     * @param response
     */
    @GetMapping("/captcha")
    public void getCaptcha(HttpServletRequest request, HttpServletResponse response) {
        String captchaText = captchaProducer.createText();
        log.info("验证码内容:{}",captchaText);
        //存储redis，配置过期时间
        //key规范 业务划分":"隔离 eg:account_service:captcha:xxx
        String key = getCaptchaKey(request);
        redisTemplate.opsForValue().set(key,captchaText,CAPTCHA_CODE_EXPIRED, TimeUnit.MILLISECONDS);
        //将生成的验证码图片写到请求返回
        BufferedImage image = captchaProducer.createImage(captchaText);
        try {
            ServletOutputStream outputStream = response.getOutputStream();
            ImageIO.write(image,"jpg",outputStream);
            outputStream.flush();
            outputStream.close();
        } catch (IOException e) {
            log.info("获取流出错:{}",e.getMessage());
        }
    }


    /**
     * 注册短信验证码
     *
     * @return
     */
    @RequestMapping("/send_code")
    public JsonData sendCode(@RequestBody SendCodeRequest sendCodeRequest, HttpServletRequest request) {
        String key = getCaptchaKey(request);

        String cacheCaptcha = redisTemplate.opsForValue().get(key);

        String captcha = sendCodeRequest.getCaptcha();

        //验证码忽略大小学
        if (StringUtils.isNotBlank(cacheCaptcha) && StringUtils.isNotBlank(captcha) && cacheCaptcha.equalsIgnoreCase(captcha)) {
            //成功
            redisTemplate.delete(key);
            return notifyService.sendCode(SendCodeEnum.USER_REGISTER,sendCodeRequest.getTo());
        } else {
            //失败
            return JsonData.buildResult(BizCodeEnum.CODE_CAPTCHA_ERROR);
        }
    }


    /**
     * 根据请求ip和User-Agent去唯一识别对应浏览器请求访问的key  User-Agent会告诉网站服务器，访问者是通过什么工具来请求的
     * @param request
     * @return
     */
    private String getCaptchaKey(HttpServletRequest request){
        String ip = CommonUtil.getIpAddr(request);
        String userAgent = request.getHeader("User-Agent");
        String key = "account_service:captcha:" + CommonUtil.MD5(ip+userAgent);
        log.info("验证码key:{}",key);
        return key;
    }

}
